package com.charles.video.system.controller;

import com.charles.video.api.domain.MemberLog;
import com.charles.video.api.domain.SysMember;
import com.charles.video.api.model.MemberLogin;
import com.charles.video.common.core.controller.BaseController;
import com.charles.video.common.core.exception.ServiceException;
import com.charles.video.common.core.responseDomain.AjaxResult;
import com.charles.video.common.core.responseDomain.R;
import com.charles.video.common.core.responseDomain.TableInfo;
import com.charles.video.common.core.utils.BcryptUtils;
import com.charles.video.common.core.utils.IpUtils;
import com.charles.video.common.core.utils.StringUtils;
import com.charles.video.common.log.annotation.Log;
import com.charles.video.common.security.utils.SecurityUtils;
import com.charles.video.system.mapper.MemberLogMapper;
import com.charles.video.system.mapper.SysMemberMapper;
import com.charles.video.system.vo.SearchMemberForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/member")
public class SysMemberController extends BaseController {

    @Autowired
    private SysMemberMapper sysMemberMapper;
    
    @Autowired
    private MemberLogMapper memberLogMapper;

    /**
     * 通过工号获取成员信息
     *
     * @param memberNum 工号
     * @return 结果
     */
    @GetMapping("/info/{memberNum}")
    public R<MemberLogin> queryMemberInfoByNum(@PathVariable("memberNum") String memberNum) {
        SysMember sysMember = sysMemberMapper.queryMemberByNum(memberNum);
        if (StringUtils.isNull(sysMember)) return R.fail("工号或密码错误");
        MemberLogin memberLogin = new MemberLogin();
        memberLogin.setMember(sysMember);
        return R.ok(memberLogin);
    }
    
    @PostMapping("/recordLoginTime")
    public void recordLoginTime(@RequestBody SysMember sysMember) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ipAddr = IpUtils.getIpAddr(request);
        Integer memberId = sysMember.getMember_id();
        MemberLog memberLog = new MemberLog();
        memberLog.setMember_id(memberId);
        memberLog.setIp_addr(ipAddr);
        memberLog.setBehavior("登录了后台系统");
        memberLogMapper.saveMemberLog(memberLog);
        sysMemberMapper.recordMemberLogin(memberId, ipAddr);
    }

    /**
     * 获取登录成员工号
     *
     * @return 结果
     */
    @GetMapping("/getMemberNum")
    public AjaxResult getMemberNum() {
        return AjaxResult.success("获取成功", SecurityUtils.getMemberNum());
    }

    @GetMapping("/queryMemberList")
    public TableInfo queryMemberList(SearchMemberForm searchMemberForm) {
        startPage();
        return getDataTable(sysMemberMapper.queryMemberList(searchMemberForm));
    }

    @GetMapping("/queryEditMemberInfo/{memberId}")
    public AjaxResult queryEditMemberInfo(@PathVariable("memberId") Integer memberId) {
        return AjaxResult.success(sysMemberMapper.queryEditMemberForm(memberId));
    }

    @Log(behavior = "新增了一个系统成员")
    @PostMapping("/addMember")
    public AjaxResult addMember(@RequestBody SysMember member) {
        String password = member.getPassword();

        if (StringUtils.isAnyBlank(member.getMember_num(), password)) {
            throw new ServiceException("修改信息为空");
        }

        if (member.getMember_num().length() < 4 || member.getMember_num().length() > 7) {
            throw new ServiceException("成员工号不符合规范");
        }

        if (member.getPassword().length() < 6 || member.getPassword().length() > 10) {
            throw new ServiceException("密码不符合规范");
        }

        if (member.getRole().equals("超级管理员") && !SecurityUtils.getMemberRole().equals("超级管理员")) {
            throw new ServiceException("无权升级为超级管理员");
        }

        if (sysMemberMapper.queryMemberByNum(member.getMember_num()) != null) {
            throw new ServiceException("工号已存在");
        }

        member.setPassword(BcryptUtils.bcryptPassword(password));
        return toAjax(sysMemberMapper.addMember(member));
    }

    @Log(behavior = "修改了系统成员")
    @PutMapping("/modifyMember")
    public AjaxResult modifyMember(@RequestBody SysMember member) {
        String password = member.getPassword();

        if (StringUtils.isAnyBlank(member.getMember_num(), password)) {
            throw new ServiceException("修改信息为空");
        }

        if (member.getMember_num().length() < 4 || member.getMember_num().length() > 7) {
            throw new ServiceException("成员工号不符合规范");
        }
        
        if (member.getRole().equals("超级管理员") && !SecurityUtils.getMemberRole().equals("超级管理员")) {
            throw new ServiceException("无权升级为超级管理员");
        }

        if (!sysMemberMapper.queryEditMemberForm(member.getMember_id()).getPassword().equals(password)) {
            if (member.getPassword().length() < 6 || member.getPassword().length() > 10) {
                throw new ServiceException("密码不符合规范");
            }
            member.setPassword(BcryptUtils.bcryptPassword(password));
        }

        return toAjax(sysMemberMapper.modifyMember(member));
    }

    @Log(behavior = "删除了系统成员")
    @DeleteMapping("/deleteMember/{memberId}")
    public AjaxResult deleteMember(@PathVariable("memberId") Integer memberId) {
        if (SecurityUtils.getMemberId().equals(memberId)) throw new ServiceException("不能删除自己");

        if (sysMemberMapper.queryEditMemberForm(memberId).getRole().equals("超级管理员"))
            throw new ServiceException("权限不足");

        return toAjax(sysMemberMapper.deleteMember(memberId));
    }

}
